package com.tianji.remark.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author WFan
 * @since 2025-03-30
 */
@Service

@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final RabbitMqHelper mqHelper;

    /**
     * 点赞或取消点赞
     *
     * @param likeRecordFormDTO
     */
    @Override
    public void likeOrCancel(LikeRecordFormDTO likeRecordFormDTO) {
        // 1. 点赞新增点赞记录，取消点赞删除点赞记录
       Boolean result = likeRecordFormDTO.getLiked() ? like(likeRecordFormDTO) : likeCancel(likeRecordFormDTO);

       // 2. 统计点赞数
        if (ObjectUtil.isEmpty(result) || !result){
            return;
        }

        Integer likeTimes = this.lambdaQuery().eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
                .eq(LikedRecord::getBizType, likeRecordFormDTO.getBizType())
                .count();
        // 3.发消息给业务方
        mqHelper.send(LIKE_RECORD_EXCHANGE,
                StrUtil.format(LIKED_TIMES_KEY_TEMPLATE, likeRecordFormDTO.getBizType()),
                new LikedTimesDTO(likeRecordFormDTO.getBizId(), likeTimes));
    }

    /**
     * 查询点赞状态
     *
     * @param bizIds
     * @return
     */

    public Set<Long> likedStatus(List<Long> bizIds) {
        if (ObjectUtil.isEmpty(bizIds)){
            return null;
        }

        List<LikedRecord> records = this.lambdaQuery().eq(LikedRecord::getUserId, UserContext.getUser())
                .in(LikedRecord::getBizId, bizIds)
                .list();
        Set<Long> bizIdList = records.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
        return bizIdList;
    }

    /**
     * 定时检测点赞数并发送业务方持久化
     *
     * @param bizType
     * @param maxBizSize
     */
    @Override
    public void checkLikedTimesAndSendMessage(String bizType, Integer maxBizSize) {
        // 没写
    }

    /**
     * 取消点赞操作
     * @param likeRecordFormDTO
     * @return
     */
    private Boolean likeCancel(LikeRecordFormDTO likeRecordFormDTO) {
        return this.remove(Wrappers.<LikedRecord>lambdaQuery()
                .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
                .eq(LikedRecord::getBizType, likeRecordFormDTO.getBizType())
                .eq(LikedRecord::getUserId, UserContext.getUser()));
    }

    /**
     * 点赞操作
     * @param likeRecordFormDTO
     * @return
     */
    private Boolean like(LikeRecordFormDTO likeRecordFormDTO) {
        Integer count = this.lambdaQuery().eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .count();
        if (count > 0){
            return false;
        }
        LikedRecord likedRecord = BeanUtil.toBean(likeRecordFormDTO, LikedRecord.class);
        likedRecord.setUserId(UserContext.getUser());
        return this.save(likedRecord);
    }
}
